package com.seeyon.apps.brwh.controller;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.brwh.kit.HttpKit;
import com.seeyon.apps.brwh.kit.StrKit;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import org.apache.commons.logging.Log;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class CustomSsoBiController extends BaseController {

    private static final Log log = CtpLogFactory.getLog(CustomSsoBiController.class);

    private static final String cookieUrl = AppContext.getSystemProperty("brwh.cookieUrl");
    private static final String biUrl = AppContext.getSystemProperty("brwh.biUrl");
    private OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");

    /**
     * 跳转帆软报表
     */
    public ModelAndView finereportSsoBiPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            String type = request.getParameter("type");
            String ref_c = request.getParameter("ref_c");
            String viewlet = request.getParameter("viewlet");
            String ref_t = request.getParameter("ref_t");
            User user = AppContext.getCurrentUser();
            Long userId = user.getId();
            V3xOrgMember v3xOrgMember = orgManager.getMemberById(userId);
            Long memberId = v3xOrgMember.getId();
            String memberCode = v3xOrgMember.getCode().trim();
//            String memberId = "Seeyon2";
//            String memberCode = "Seeyon2";
            if("".equals(memberCode)){
                CtpView ctpView = new CtpView("请联系管理员维护员工工号!");
                modelAndView.setView(ctpView);
            }
            log.info("帆软跳转获取当前登录人员工号:"+memberCode);
            String cookie_url = cookieUrl+"&fine_username="+memberCode+"&fine_password="+memberId;
            log.info("帆软获取cookie信息接口地址:"+cookie_url);
            Map<String, Object> headers = new HashMap<String, Object>();
            String cookie = HttpKit.get(cookie_url, headers);
            log.info("获取cookie返回信息:"+cookie);
            if(cookie.contains("accessToken")){
                cookie = cookie.replace("callback(","");
                cookie = cookie.replace(")","");
                JSONObject jsonObject = JSONObject.parseObject(cookie);
                String accessToken = StrKit.str(jsonObject.get("accessToken"));
                log.info("获取到的accessToken:"+accessToken);
//                String ssoBiUrl = biUrl+"/"+type+"?ref_c="+ref_c+"&viewlet="+viewlet+"&ref_t="+ref_t;
                String ssoBiUrl = biUrl+"?token="+accessToken+"&url=webroot/decision/view/"+type+"&ref_c="+ref_c+"&viewlet="+viewlet+"&ref_t="+ref_t;
                log.info("报表跳转URL地址:"+ssoBiUrl);
                modelAndView.setView(new RedirectView(ssoBiUrl));
            }else{
                CtpView ctpView = new CtpView("获取帆软报表系统token失败!");
                modelAndView.setView(ctpView);
            }
        } catch (Exception e) {
            log.error("跳转帆软报表页面失败:", e);
        }
        return modelAndView;
    }

    /**
     * ModelAndView 返回失败处理页面
     */
    private static final class CtpView implements View {
        private final String content;

        private CtpView(String content) {
            this.content = content;
        }

        public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0L);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print("<center><b style=\"color:red;\">" + this.content + "</b></center>");
        }

        public String getContentType() {
            return "text/html;charset=UTF-8";
        }
    }
}
